package com.hmall.search.service;

import com.alibaba.fastjson.JSON;
import com.hmall.search.mapper.ItemMapper;
import com.hmall.search.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class DataServiceCRUD {
    @Autowired
    public ItemMapper itemMapper;

    private RestHighLevelClient client;

    private DataServiceCRUD() {
        client = new RestHighLevelClient(RestClient
                .builder(HttpHost.create("192.168.119.128:9200")));
    }

    public void deleteById(long id) throws IOException {
        Item item = itemMapper.selectById(id);
        ItemDoc itemDoc = new ItemDoc(item);
        DeleteRequest request = new DeleteRequest("item", itemDoc.getId().toString());
        client.delete(request,RequestOptions.DEFAULT);
    }

    public void Update(long id) throws IOException {
        Item item = itemMapper.selectById(id);
        ItemDoc itemDoc = new ItemDoc(item);
        if (itemDoc.getStatus()==1){
            IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
        }else {
            deleteById(id);
        }


    }
}
